package com.situ.crm.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.situ.crm.mapper.SaleChanceCustomMapper;
import com.situ.crm.pojo.bo.SaleChanceSearchBO;
import com.situ.crm.pojo.vo.SaleChanceVO;
import com.situ.crm.util.Result;
import com.situ.crm.pojo.entity.SaleChance;
import com.situ.crm.pojo.entity.User;
import com.situ.crm.mapper.SaleChanceMapper;
import com.situ.crm.mapper.UserRoleMapper;
import com.situ.crm.service.ISaleChanceService;
import com.situ.crm.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SaleChanceServiceImpl implements ISaleChanceService {
	@Autowired
	private SaleChanceMapper saleChanceMapper;
	@Autowired
	private SaleChanceCustomMapper saleChanceCustomMapper;
	@Autowired
	private UserRoleMapper userRoleMapper;
	
	@Override
	public Result selectByPage(Integer page, Integer limit, SaleChanceSearchBO saleChanceSearchBO) {
		//1、使用PageHelper插件设置分页
		PageHelper.startPage(page, limit);
		//2、执行查询
		// 如果是销售人员，就只能查看自己的营销记录
		List<SaleChanceVO> list = new ArrayList<>();
		User user = (User) UserContext.session.getAttribute(UserContext.USER_IN_SESSION);
		Integer xiaoShouRoleCount = userRoleMapper.selectXiaoShouRoleCountByUserId(user.getId());
		// 如果用户是销售角色，就只能查看自己下面的营销机会
//		if (xiaoShouRoleCount > 0) {
//			list = saleChanceCustomMapper.selectByUserId(user.getId());
//		} else {// 默认查看所有
//			list = saleChanceCustomMapper.selectByPage(saleChance);
//		}
		list = saleChanceCustomMapper.selectByPage(saleChanceSearchBO);
		//3、使用PageInfo对结果进行包装
		PageInfo pageInfo = new PageInfo(list);
		Integer count = (int) pageInfo.getTotal();//得到总数量

		return Result.success("查询成功", list, count);
	}

	@Override
	public boolean deleteById(Integer id) {
		int count = saleChanceMapper.deleteByPrimaryKey(id);
		return  count == 1 ? true : false;
	}


	@Override
	public SaleChance selectByPrimaryKey(Integer saleChanceId) {
		return saleChanceMapper.selectByPrimaryKey(saleChanceId);
	}

	@Override
	public boolean add(SaleChance saleChance) {
		// 根据userId是否分配判断status状态是未分配还是已分配
		// 分配状态 0 未分配 1 已分配
		if (saleChance.getUserId() != null) {
			saleChance.setStatus(1);
		} else {
			saleChance.setStatus(0);
		}
		// 客户开发状态 0 未开发 1 开发中 2 开发成功 3 开发失败
		saleChance.setDevResult(0);
		// 将角色插入到数据库中
		int count = saleChanceMapper.insert(saleChance);
		return count == 1 ? true : false;
	}
	
	
	@Override
	public boolean update(SaleChance saleChance) {
		// 将角色插入到数据库中
		int count = saleChanceMapper.updateByPrimaryKey(saleChance);
		return count == 1 ? true : false;
	}
}
